import {Component, ViewEncapsulation, ViewChild, Input, Output, EventEmitter} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {IdeaService} from '../../../services/app.idea';
import {UserService} from '../../../services/app.user';
import {Utility} from '../../../services/app.utility';
import {AuthenticationHelper} from '../../../app.authentication';
import {BaThemeSpinner}  from '../../../theme/services';
import {Modal} from 'ngx-modal';
import {Country} from './country';
import {ImageCropperComponent, CropperSettings} from 'ng2-img-cropper';
import {Constants} from '../../../../app/common/app.constants';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'userprofile',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./profile.scss'],
    templateUrl: './profile.html',
    providers: [Country]
})
export class UserProfile {
    @Input()
    constants:Constants;
    public start:any;
    public end:any;
    public check:any;
    public viewDetailIdea:any;
    public profileEditModal:any;
    public abuseIdea:any;
    public activities:any;
    public activityCount:any;
    public fileUpload:any;
    public profileImageUser:any;
    public profileEmail:string;
    public profileLocation:string;
    public profileLocationCity:string;
    public profileLocationCountry:string;
    public profileDate:any;
    public profileIdeaCount:any;
    public profileCommentCount:any;
    public profileVoteCount:any;
    public profileLikesCount:any;
    public aboutMe:any;
    public commentsOnUsersIdea:any;

    @Input()
    userId:string;
    @Output()
    notifyParent:EventEmitter<any> = new EventEmitter();
    @ViewChild('ViewDetailIdeaModel')
    public ViewDetailIdeaModel:Modal;
    @ViewChild('abuseModal')
    public abuseModal:Modal;
    @Output()
    notifyUserParent:EventEmitter<any> = new EventEmitter();


    public form:FormGroup;
//    public profileImagelocal:any = 'http://144.214.55.144:3001';
   // public profileImagelocal:any = 'http://localhost:3001';
   public profileImagelocal:any = 'http://45.79.103.182:5002';
 
    private uploadImage:boolean;
    private showEdit:boolean;
    public showActivity:boolean;
    public data:any = {};
    public userIDForProfile:any;
    public activityList:any = {};
    public cropperSettings:CropperSettings;
    public profileData:any;
    public cursorPointerProfille:boolean;
    public countries:any;
    public profilephotoinformation:boolean;
    public profileName:any;
    public profileImage:any;

    @ViewChild('Modal')
    private myModal:Modal;
    @ViewChild('cropper')
    public cropper:ImageCropperComponent;
    public commentListOfIdea:any = {};

    constructor(public utility:Utility, private spinner:BaThemeSpinner, private formGroups:FormBuilder, private authentication:AuthenticationHelper, private userService:UserService, private IdeaService:IdeaService, private Utility:Utility, private  country:Country) {
        this.constants = new Constants();
        this.form = formGroups.group({
            'profileUserFirstName': ['', Validators.compose([Validators.required])],
            'profileUserLastName': ['', Validators.compose([Validators.required])],
            'profileUserAddress': ['', []],
            'profileUserCity': ['', []],
            'profileUserState': ['', []],
            'profileUserCountry': ['', []],
            'profileUserAboutme': ['', []]
        });
        this.cursorPointerProfille = false;
        if (this.utility.clickFromProfile) {
            this.cursorPointerProfille = true;
        }
        this.userIDForProfile = '';
        if (this.utility.UserPageInfo) {
            this.userIDForProfile = this.utility.UserPageInfo.user;
        }

        this.showEdit = true;
        this.cropperSettings = new CropperSettings();
        this.cropperSettings.width = 100;
        this.cropperSettings.height = 100;
        this.cropperSettings.croppedWidth = 100;
        this.cropperSettings.croppedHeight = 100;
        this.cropperSettings.canvasWidth = 400;
        this.cropperSettings.canvasHeight = 300;
        this.cropperSettings.noFileInput = true;
        this.countries = this.country.country;
        this.uploadImage = true;
        this.activityList = {
            '_id': '',
            'skipItem': 0,
            'itemsperPage': 10,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.commentListOfIdea = {
            skipCommentsItem: 0,
            commentsPerPage: 6,
        };

        // Function for call viewprofile
        this.viewProfile();

        this.start = 0;
        this.check = 0;

        // Function for start timeline count
        this.startCount();

    }

    // Notify Parent for Open Modal PopUp
    getfullIdea(idea, user) {
        let data1 = {
            'idea': idea,
            'user': user
        };
        this.notifyUserParent.emit(data1);
        this.spinner.showProgress();
        let input = {
            ideaId: idea,
            userId: user
        };
        this.IdeaService.getIdeaIdForAbuse(input).subscribe(
            data => this.getIdeaSuccess(data, input),
            error => this.getIdeaFail(error)
        );
    }

    // Function call when idea abuse id got successfully
    public getIdeaSuccess(ideainfo, input) {
        this.getIdeaComments(ideainfo, input);
    }

    // Function call when idea abuse id failed to find
    public getIdeaFail(error) {
    }

    // Function for idea comment API call
    public getIdeaComments(ideainfo, input) {
        let cardData = {
            'ideaId': input.ideaId,
            'skipItem': this.commentListOfIdea.skipCommentsItem,
            'itemsperPage': this.commentListOfIdea.commentsPerPage,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.IdeaService.getcardComment(cardData).subscribe(
            data => this.getcommentsuccess(data, ideainfo),
            error => this.getcommentfail(error)
        );

    }

    // Function call if comment successfully
    public getcommentsuccess(data, ideainfo) {
        this.spinner.hideProgress();
        let modalData = ideainfo;
        if(modalData.length) {
            modalData[0].data = data;
            this.viewDetailIdea = modalData[0];
        }
        if (this.utility.clickFromProfile) {
            this.ViewDetailIdeaModel.open();
        }
    }

    // Function call if comment failed
    public getcommentfail(data) {
        this.spinner.hideProgress();
    }

    // Function for check file changes int profile image
    public fileChangeListener($event) {
        var that = this;
        var image:any = new Image();
        var file:File = $event.target.files[0];
        this.profilephotoinformation = false;
        if ($event.target.files.length != 0) {
            if (file.type.substring(0, 5) == 'image' && file.size <= 3145728) {
                var myReader:FileReader = new FileReader();
                myReader.onloadend = function (loadEvent:any) {
                    image.src = loadEvent.target.result;
                    that.cropper.setImage(image);
                };
                myReader.readAsDataURL(file);
                this.profileEditModal = true;
            }
            else {
                this.profilephotoinformation = true;
            }
        }
        $event.target.value = '';
    }

    // Function for get user profile info
    public viewProfile() {
        if (this.userIDForProfile) {
            this.hideEdit();
            let input = {
                '_id': this.userIDForProfile
            };
            this.userService.userProfile(input).subscribe(
                data => this.userProfilesucces(data, undefined),
                error => this.userProfilefail(error)
            );
        } else {
            this.userService.userProfile({}).subscribe(
                data => this.userProfilesucces(data, undefined),
                error => this.userProfilefail(error)
            );
        }

    }

    // Function for get user profile data for table
    public  getUserProfileData(id, skip, act):void {
        this.activities = [];
        this.activityList = {
            '_id': '',
            'skipItem': 0,
            'itemsperPage': 10,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.activityList._id = id;
        if (skip === undefined)
            skip = 0;
        this.activityList.skipItem = skip;
        this.userService.userProfile(this.activityList).subscribe(
            data => this.userProfilesucces(data, act),
            error => this.userProfilefail(error)
        );
    }

    // Function for hide edit option if not own user
    public hideEdit() {
        this.showEdit = false;
    }

    // Function for reset profile page content
    public resetProile() {
        this.profileImage = '';
        this.profileImageUser = '';
        this.profileName = '';
        this.profileEmail = '';
        this.profileLocation = '';
        this.profileLocationCity = '';
        this.profileLocationCountry = '';
        this.profileDate = '';
        this.profileIdeaCount = '';
        this.profileCommentCount = '';
        this.profileVoteCount = '';
        this.profileLikesCount = '';
        this.aboutMe = '';
    }

    // Function for enter profile page content
    public  userProfilesucces(data, act) {
        this.profileData = data;
        this.profileImage = this.profileImagelocal + this.profileData.profile.profileImageURL.slice(1);
        this.profileImageUser = this.profileImagelocal + this.profileData.profile.profileImageURL.slice(1);
        if (data.profile.firstName != 'undefined' && data.profile.firstName)
            this.profileName = this.profileData.profile.firstName + ' ';
        if (data.profile.lastName != 'undefined' && data.profile.lastName)
            this.profileName += this.profileData.profile.lastName;
        this.profileEmail = this.profileData.profile.email;
        this.profileLocation = this.profileData.profile.address;
        this.profileLocationCity = this.profileData.profile.city + ((this.profileData.profile.city.toString().length > 0 && this.profileData.profile.state.toString().length > 0 ) ? (', ' + this.profileData.profile.state) : (' ' + this.profileData.profile.state));
        this.profileLocationCountry = this.profileData.profile.country;
        this.profileDate = this.Utility.getFormattedDateForTree(this.profileData.profile.createdAt);
        this.profileIdeaCount = this.profileData.ideaCount;
        this.profileCommentCount = this.profileData.commentCount;
        this.profileVoteCount = this.profileData.voteCount;
        this.profileLikesCount = this.profileData.likesCount;
        this.commentsOnUsersIdea = data.commentsOnUsersIdea;
        this.aboutMe = this.profileData.profile.aboutMe;
        // For activity log
        if (act === undefined) {
            this.activities = data.activity;
        } else {
            this.activities = act.concat(data.activity);
        }

        if (data.activity.length > 0) {
            this.showActivity = false;
        } else {
            this.showActivity = true;
        }

        if (data.activity) {
            this.activityCount = data.activity.length;
        }
        this.utility.UserPageInfo = '';
    }

    // Function for edit profile changes failed to load
    public userProfilefail(error) {
        this.spinner.hideProgress();

    }

    // Function for update user profile info
    public userUpdateProfile(Values) {
        this.spinner.showProgress();
        if (this.form.valid) {
            let data = {
                "_id": this.profileData.profile._id,
                "firstName": Values.profileUserFirstName,
                "lastName": Values.profileUserLastName,
                "address": Values.profileUserAddress,
                "city": Values.profileUserCity,
                "state": Values.profileUserState,
                "country": Values.profileUserCountry,
                "aboutMe": Values.profileUserAboutme
            };
            this.userService.userProfileUpdateChange(data).subscribe(
                data => this.userProfileUpdatesucces(data),
                error => this.userProfileUpdatefail(error)
            );
        }
    }

    // Function for update user profile info successfully
    public userProfileUpdatesucces(data) {
        this.spinner.hideProgress();
        toastr.success(this.constants.POFILEUPDATESUCCESSFULLY);
        this.authentication.userValueChangedEvent(data);
        this.profileName = data.firstName + ' ' + data.lastName;
        this.profileData.profile.firstName = data.firstName;
        this.profileData.profile.lastName = data.lastName;
        this.profileData.profile.address = data.address;
        this.profileData.profile.state = data.state;
        this.profileData.profile.city = data.city;
        this.profileData.profile.country = data.country;
        this.profileData.profile.aboutMe = data.aboutMe;
        this.profileLocation = this.profileData.profile.address;
        this.profileLocationCity = this.profileData.profile.city + ((this.profileData.profile.city.toString().length > 0 && this.profileData.profile.state.toString().length > 0 ) ? (', ' + this.profileData.profile.state) : (' ' + this.profileData.profile.state));
        this.profileLocationCountry = this.profileData.profile.country;
        this.aboutMe = this.profileData.profile.aboutMe;
        this.authentication.setUser(data);
        this.myModal.close();
        this.onTypeEvent();
    }

    // Function for user profile info fail
    public userProfileUpdatefail(error) {
        this.spinner.hideProgress();
    }

    // Function for user  image crop and save
    public saveCropImage() {
        this.spinner.showProgress();
        let data = {
            img: this.data.image
        };
        this.userService.userProfileImageSaved(data).subscribe(
            data => this.userProfileImageSavedSuccess(data),
            error => this.userProfileImageFailed(error)
        );
    }

    // Function for user image successfully upload
    public userProfileImageSavedSuccess(data) {
        toastr.success(this.constants.IMAGEUPLOADSUCCESSFULLY);
        this.profileImageUser = this.profileImagelocal + data.profileImageURL.slice(1);
        this.profileImage = this.profileImagelocal + data.profileImageURL.slice(1);
        this.uploadImage = true;
        this.profileData.profile.profileImageURL = data.profileImageURL;
        this.authentication.setUser(data);
        this.authentication.userValueChangedEvent(data);
        this.spinner.hideProgress();
    }

    // Function for user profile image fail to upload
    public userProfileImageFailed(error) {
        this.spinner.hideProgress();
    }

    // Function for user profile modal close
    public profileEditModalClose() {
        this.uploadImage = true;
        this.fileUpload = false;
    }


    // Function for get user profile info
    public getProfileInfo() {
        this.form.get('profileUserFirstName').setValue(this.profileData.profile.firstName);
        this.form.get('profileUserLastName').setValue(this.profileData.profile.lastName);
        this.form.get('profileUserAddress').setValue(this.profileData.profile.address);
        this.form.get('profileUserCity').setValue(this.profileData.profile.city);
        this.form.get('profileUserState').setValue(this.profileData.profile.state);
        this.form.get('profileUserCountry').setValue(this.profileData.profile.country);
        this.form.get('profileUserAboutme').setValue(this.profileData.profile.aboutMe);
        this.profileImage = this.profileImagelocal + this.profileData.profile.profileImageURL.slice(1);
    }

    //  Convert Date to MM/DD/YYYY
    public formateDate(dates):any {
        return this.utility.getFormattedDate(dates);
    }

    // Function for format date
    public formateDatewithTime(dates):any {
        return this.utility.getAgoDate(this.utility.getFormattedDate(dates));
    }

    // Function for get more data on click link
    public getMoreActivity(act) {
        this.activityList.skipItem += this.activityList.itemsperPage;
        this.getUserProfileData(this.profileData.profile._id, this.activityList.skipItem, act);
    }

    // Function for open abuse modal
    getNotificationModal(idea) {
        this.abuseIdea = idea;
        this.abuseModal.open();
    }

    // Function for close abuse modal and clear data
    getNotificationAbuseModal(evt) {
        this.abuseIdea = null;
        this.abuseModal.close();
    }

    // Function for call profile function to clear prev data
    public refreshActivity() {
        this.viewProfile();
    }

    // User log for keystroke event
    public onTypeEvent() {

        let input = {
            'target': this.constants.FILLEDITUSERFORM,
            'value': 'edit user profile',
            'action': 'keystroke'
        };
        this.userService.setUserLogs(input).subscribe();
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

    }
}
